<template>
	<div>
		<div class="content_title">
		<span style="color: #222222;font-size: 24px;font-weight: 400;">{{title}}</span>
		</div>
		<div class="formContent">
			<el-form :rules="rules" :model="formData" ref="ruleForm" class="demo-ruleForm">
			   <el-row style='margin-bottom: 20px;'>发布积分任务</el-row>
			   <el-row :gutter='50'>
			   	   <el-col :lg='6'>
			   	   	   
			   	   	   <el-form-item>
			   	   	   	    <label>积分历史任务模板</label>
		          			  <el-select @change='getHistoryActivityDetail' clearable  v-model="formData.HistoryValue" placeholder="请选择" style="width: 100%">
												<el-option
													v-for="item in History"
													:key="item.value"
													:label="item.label"
													:value="item.value">
												</el-option>
											</el-select>
				        </el-form-item>
				        <el-form-item prop='MissionTitle'>
				        	<label>任务标题</label>
		          			<el-input v-model="formData.MissionTitle" placeholder='请输入任务标题'  style="width: 100%" size="small"></el-input>
				        </el-form-item>
				        <el-form-item  prop='DegreeValue'>
				        	<label>任务难度</label>
		          			  <el-select v-model="formData.DegreeValue" placeholder="请选择" style="width: 100%">
												<el-option
													v-for="item in Degree"
													:key="item.value"
													:label="item.label"
													:value="item.value">
												</el-option>
											</el-select>
				        </el-form-item>
				        <el-form-item prop='MissionLimit'>
				        	<label>时间限制</label>
		          			<el-input v-model="formData.MissionLimit"  placeholder='请输入任务完成时限' style="width: 100%" size="small"><template slot="append">分钟</template></el-input>
				        </el-form-item>
				        <el-form-item prop='MissionScore'>
				        	<label>任务积分</label>
		          			<el-input :maxlength='5' v-model="formData.MissionScore"  placeholder='请输入完成任务得到的积分数' style="width: 100%" size="small"></el-input>
				        </el-form-item>
						<el-form-item prop='NoValue'>
							<label>任务优先级</label>
							<el-select v-model="formData.NoValue" placeholder="请选择" style="width: 100%">
								<el-option
									v-for="item in No"
									:key="item.value"
									:label="item.label"
									:value="item.value">
								</el-option>
							</el-select>
						</el-form-item>
			   	   </el-col>
			   	   <el-col :lg='6'>
			   	   	   
			   	   	   <el-form-item prop='StoreValue'>
			   	   	   	    <label>任务店铺</label>
		          			<el-select v-model="formData.StoreValue" placeholder="未选择" style="width: 100%">
		          				<el-option
		          					v-for='(item,index) in storeList'
		          					:key="item.StoreId"
		          					:label="item.label"
		          					:value="item.value">
		          				</el-option>
		          			</el-select>
				        </el-form-item>
				        <el-form-item prop='MissionNumber'>
				        	<label>任务人数</label>
		          			<el-input v-model="formData.MissionNumber" placeholder='请输入任务人数'  style="width: 100%" size="small"></el-input>
				        </el-form-item>
				        <el-form-item prop='CountValue'>
				        	<label>任务时长</label>
		          			<el-select v-model="formData.CountValue" placeholder="请选择" style="width: 100%">
		          				<el-option
		          					v-for="item in Count"
		          					:key="item.value"
		          					:label="item.label"
		          					:value="item.value">
		          				</el-option>
		          			</el-select>
				        </el-form-item>
				        <el-form-item prop='ApproveValue'>
				        	<label>是否自动审核</label>
		          			<el-select v-model="formData.ApproveValue" placeholder="请选择" style="width: 100%">
		          				<el-option
		          					v-for="item in Approve"
		          					:key="item.value"
		          					:label="item.label"
		          					:value="item.value">
		          				</el-option>
		          			</el-select>
				        </el-form-item>
								<el-form-item>
									<label>定时发布</label>
										    <el-date-picker
													style="width:100%"
													v-model="formData.Timevalue"
													type="datetime"
													placeholder="选择日期时间"
													value-format='yyyy-MM-dd HH:mm'
													default-time="12:00:00" change="TimeChange()">
												</el-date-picker>
								</el-form-item>
								<el-form-item>
								<label>用户组筛选</label>
									<el-select v-model="formData.GroupValue" placeholder="请选择" clearabled style="width: 100%">
										<el-option
											v-for="(item,index) in userGroupList"
											:key="item.GroupStatus"
											:label="item.label"
											:value="item.value">
										</el-option>
									</el-select>
								</el-form-item>
			   	   </el-col>
			   	    <el-col :lg='5'>
	
			   	   	   <el-form-item prop='Introduce'>
			   	   	   	    <label>活动简介</label>
		          			<el-input v-model="formData.Introduce" type='textarea' placeholder='请输入任务内容' :rows='26' style="width: 100%" size="small"></el-input>
				        </el-form-item>
			   	   </el-col>            
			   </el-row>
				
			</el-form>
			<br />
		    <el-form v-if="pageKind == 'new'">
				 <el-row>
						 <label style="color: #B0BAC9;font-size: 16px;line-height: 30px;">任务步骤示例</label>
						 <div>
						 	<img class="picItem" v-for="item in picList1" :src="item.path"></img>
						 	<label class="checkPicture" for="upload1" >+</label>
						 	<input id="upload1" name="Pic" type="file" style="display: none;" @change="getFiles1"/>
						 </div>
				 </el-row>
				 <br />
				 <el-row>
						 <label style="color: #B0BAC9;font-size: 16px;line-height: 30px;">任务截图示例</label>	
						 <div>
						 	<img class="picItem" v-for="item in picList2" :src="item.path"></img>
						 	<label class="checkPicture" for="upload2">+</label>
						 	<input id="upload2"  name="Pic" type="file" style="display: none;"  @change="getFiles2"/>
						 </div>		 
			    </el-row>	
					<br />
			 </el-form>
			 
				 <el-row >
					   	  <el-button v-if="pageKind == 'new'" class="el-button" :disabled="ifSubmit" style="background: #1989FA;color: white;" @click="submitUpload('ruleForm')">发布</el-button>
						  <button class="el-button backBtn" style="background: white;border:1px solid rgba(220,223,230,1);" @click="goBack">返回</button>
				 </el-row>	
		 </div>
	 </div>
</template>

<script>

	import 	HeaderContent from '../components/main_content'
	import global from './global'
	export default {
    name: "积分任务",
    inject:['reload'],
    mounted(){
    
    	if(this.$route.params.pageKind == 'new'){
    		this.initData();
    		
    	}else{
    		this.getActivityDetail();
    		$('input').attr('placeholder','')
    		$('input').attr('readonly','readonly')
    	}
    	
    	
    	if(this.$route.params.taskKind == '0' && this.$route.params.pageKind == 'new'){
    		this.title = '发布积分任务';
    		this.submitUrl = 'PcAddScoreMission/'
    	}else if(this.$route.params.taskKind == '1' && this.$route.params.pageKind == 'new'){
    		this.title = '发布福利任务';
    		this.submitUrl = 'PcAddMoneyMission/'
    	}else{
    		this.title = '任务详情'
    	}
    	
    	
    },
    components:{
    	HeaderContent
    },
    data() {
    	return {
    		title:'',
			uploadUrl:'api/AddModelMissionExampleCert/',
        	pageKind: this.$route.params.pageKind,
        	submitUrl: '',
    		picList:[
    			{path:'../assets/img/nav3.png'},
    			{path:'../assets/img/nav2.png'}
    		],
			    formData:{
			    	MissionTitle: "",
			    	DegreeValue: "1",
			    	ApproveValue:"1",
			    	NoValue:"1",
			    	MissionLimit:"",
			    	MissionScore:"",
			    	StoreValue:"",
			    	Introduce:"",
			    	GroupValue:"",
			    	MissionNumber:"",
			    	Timevalue:"",
			    	CountValue:"1",
			    },
			    rules:{
			    	MissionTitle:[{ required: true, message: '请填写任务标题', trigger: 'blur' }],
			    	DegreeValue:[{ required: true, message: '请选择任务难度', trigger: 'blur' }],
			    	ApproveValue:[{ required: true, message: '请选择是否自动审核', trigger: 'blur' }],
			    	NoValue:[{required: true, message: '请选择任务优先级', trigger: 'blur' }],
			    	MissionLimit:[{ required: true, message: '请输入时间限制', trigger: 'blur' }],
			    	MissionScore:[{ required: true, message: '请输入任务积分', trigger: 'blur' }],
			    	StoreValue:[{ required: true, message: '请选择任务店铺', trigger: 'blur' }],
			    	Introduce:[{ required: true, message: '请输入活动简介', trigger: 'blur' }],
			    	MissionNumber:[{ required: true, message: '请输入任务人数', trigger: 'blur' }],
			    	CountValue:[{ required: true, message: '请选择任务时常', trigger: 'blur' }],
			    },
				MissionId:"",
				History:[],
				HistoryValue:"",
				Degree:[
					{
						value:"1",
						label:"一星"
					},{
						value:"2",
						label:"二星"						
					},{
						value:"3",
						label:"三星"
					},{
						value:"4",
						label:"四星"
					},{
						value:"5",
						label:"五星"
					}
				],
				No:[
					{
						value:"1",
						label:"一级",
					},{
						value:"2",
						label:"二级",
					},{
						value:"3",
						label:"三级",
					},{
						value:"4",
						label:"四级",
					},{
						value:"5",
						label:"五级",
					}
				],
				Store:[{label:'1',value:'1'}],
				Count:[
					{
						value:"1",
						label:"1小时"
					},{
						value:"3",
						label:"3小时"
					},{
						value:"6",
						label:"6小时"
					},{
						value:"9",
						label:"9小时"
					},{
						value:"12",
						label:"12小时"
					},{
						value:"15",
						label:"15小时"
					},{
						value:"18",
						label:"18小时"
					},{
						value:"24",
						label:"24小时"
					},{
						value:"48",
						label:"48小时"
					},{
						value:"72",
						label:"72小时"
					}
				],
				Approve:[
					{
						value:"1",
						label:"是"
					},{
						value:"0",
						label:"否"
					}
				],
				Group:[{label:'1',value:'1'}],
				picList1: [],
				picList2: [],
				TimeSelect:false,//定时发布时间选择flag
				storeList: [],
				userGroupList: [],
				length: 0,
				length2: 0,
				fileObject: [],
				fileObject2: [],
				ifSubmit: false,
    	}
    },
    methods:{
			initData(){
				let _this = this;
				global.$http({
						method:'get',
						url:global.urlAll+'PcSetMissionSelect/',
						headers:{
							'Content-Type':'application/x-www-form-urlencoded',
							'cache-control': 'no-cache, no-store',
							'Pragma': 'no-cache'
						},
						params:{
							BusinessId:$.cookie("userId"),
							Kind:0
							
						}
					}).then((res)=>{
						if(res.data.Success="true"){
							_this.History = res.data.MissionInfo;
							_this.storeList = res.data.StoreInfo;
							_this.userGroupList = res.data.GroupInfo;
							console.log(_this.userGroupList)
						}else{
							_this.$message("网络异常，请重试")
						}
					})
			},
			getHistoryActivityDetail(e){
				console.log(e)
				let MessionId = e;
				let _this = this;
				let detailUrl = '';
				if(this.$route.params.taskKind == '0'){
					detailUrl = 'ScoreMissionDetail/';
				}else{
					detailUrl = 'MoneyMissionDetail/';
				}
				global.$http({
						method:'get',
						url:global.urlAll+detailUrl,
						headers:{
							'Content-Type':'application/x-www-form-urlencoded',
							'cache-control': 'no-cache, no-store',
							'Pragma': 'no-cache'
						},
						params:{
							BusinessId:$.cookie("userId"),
							MissionId: MessionId
						}
					}).then((res)=>{
						if(res.data.Success="true"){
							_this.formData.MissionTitle = res.data.Title;
							_this.formData.DegreeValue = res.data.Degree;
							_this.formData.ApproveValue = res.data.Check;
							_this.formData.NoValue = res.data.SortNo;
							_this.formData.MissionLimit = res.data.TimeLimit;
							_this.formData.MissionScore = res.data.Score;
							_this.formData.StoreValue = res.data.StoreName;
							_this.formData.Introduce = res.data.Content;
							_this.formData.GroupValue = res.data.GroupName;
							_this.formData.MissionNumber = res.data.Number;
							_this.formData.Timevalue = res.data.Timing;
							_this.formData.CountValue = res.data.TimeLong;
							
						}else{
							_this.$message("网络异常，请重试")
						}
					})
			},
			getFiles1(e){
				let _this =this;
				let formEl = document.getElementById('upload1').files;
				console.log(formEl)
				if(!e || !window.FileReader) return
	    		let reader = new FileReader();
	    		reader.readAsDataURL(formEl[0])
	    		reader.onloadend = function(){
	    			console.log(this.result)
	    			_this.fileObject.push(this.result)
	    	   		_this.picList1.push({path:this.result})
	    		}
			},
			getFiles2(e){
				let _this =this;
				let formEl = document.getElementById('upload2').files[0];
				
				if(!e || !window.FileReader) return
	    		let reader = new FileReader();
	    		reader.readAsDataURL(formEl)
	    		reader.onloadend = function(){
	    			_this.fileObject2.push(this.result)
	    	   		_this.picList2.push({path:this.result})
	    		}
			},
			uploadImage(){
				console.log(this.fileObject);
				let _this = this;
				if(this.length == this.fileObject.length){
					console.log(false)
				}else{
					 let picForm = new FormData();
					 picForm.append('Pic',this.fileObject[this.length]);
					 picForm.append('Status', '1');
					 picForm.append('MissionId', this.MissionId);
					let config = {
						           header:{
						             	 'Content-Type': 'application/x-www-form-urlencoded'
						              }
						         };
	    			const formRequest = global.$http.create({ 
					      			widthCredentials : true
					      		})
					formRequest.post('/api/AddModelMissionExampleCert/',picForm,config).then((res)=>{
						if(res.data.Success == 'true'){
						  _this.length += 1;
						  _this.uploadImage();
						 }
					})
				}
				
				
			},
			uploadImage2(){
				console.log(this.fileObject);
				let _this = this;
				if(this.length2 == this.fileObject2.length){
					console.log(false)
				}else{
					 let picForm = new FormData();
					 picForm.append('Pic',this.fileObject2[this.length2]);
					 picForm.append('Status', '0');
					 picForm.append('MissionId', this.MissionId);
					let config = {
						           header:{
						             	 'Content-Type': 'application/x-www-form-urlencoded'
						              }
						         };
	    			const formRequest = global.$http.create({ 
					      			widthCredentials : true
					      		})
					formRequest.post('/api/AddModelMissionExampleCert/',picForm,config).then((res)=>{
						if(res.data.Success == 'true'){
						  _this.length2 += 1;
						  _this.uploadImage2();
						}
						
					})
				}
				
				
			},
			TimeChange(){
				this.TimeSelect = true
			},
			//发布任务
			submitUpload(formName){
			    let allInput = $('input');
			     this.$refs[formName].validate((valid) => {
		          if (valid) {
		           this.$confirm('是否确认删除?', '提示', {
			         confirmButtonText: '确定',
			         cancelButtonText: '取消',
			         type: 'warning'
			       }).then(() => {
						let _this = this;
						this.ifSubmit = true;
						var params = new URLSearchParams();
						params.append("Title",_this.formData.MissionTitle);
						params.append("Diff",_this.formData.DegreeValue);
						params.append("Status",_this.formData.ApproveValue);
						params.append("No",_this.formData.NoValue);
						params.append("TimeLimit",_this.formData.MissionLimit);
						params.append("Score",_this.formData.MissionScore);
						params.append("Store",_this.formData.StoreValue);
						params.append("Content",_this.formData.Introduce);
						params.append("GroupId",_this.formData.GroupValue.split('_')[0]);
						params.append("GroupStatus",_this.formData.GroupValue.split('_')[1]);
						params.append("Number",_this.formData.MissionNumber);
						params.append("Timing",_this.formData.Timevalue);
						params.append("TimeLong",_this.formData.CountValue);
						params.append("BusinessId",$.cookie("userId"));				
						global.$http({
								method:'post',
								url:global.urlAll + _this.submitUrl,
								headers:{
									'Content-Type':'application/x-www-form-urlencoded',
									'cache-control': 'no-cache, no-store',
									'Pragma': 'no-cache'
								},
								data:params
							}).then((res) => {
								  
								_this.ifSubmit = false;
								if(res.data.Success=="true"){
									_this.MissionId = res.data.MissionId;
									_this.goBack();
									setTimeout(function(){
										_this.$message('上传成功');
										
									},2000)
									
									_this.uploadImage();
									_this.uploadImage2();
									
								}else{
									_this.$message(res.data.error)
								}
							})	
						})
		          } else {
		            console.log('error submit!!');
		            return false;
		          }
		        });	
					
			},
			getActivityDetail(){
				let _this = this;
				let detailUrl = '';
				if(this.$route.params.taskKind == '0'){
					detailUrl = 'ScoreMissionDetail/';
				}else{
					detailUrl = 'MoneyMissionDetail/';
				}
				global.$http({
						method:'get',
						url:global.urlAll+detailUrl,
						headers:{
							'Content-Type':'application/x-www-form-urlencoded',
							'cache-control': 'no-cache, no-store',
							'Pragma': 'no-cache'
						},
						params:{
							BusinessId:$.cookie("userId"),
							MissionId: _this.$route.params.MissionId
						}
					}).then((res)=>{
						if(res.data.Success="true"){
							_this.formData.MissionTitle = res.data.Title;
							_this.formData.DegreeValue = res.data.Degree;
							_this.formData.ApproveValue = res.data.Check;
							_this.formData.NoValue = res.data.SortNo;
							_this.formData.MissionLimit = res.data.TimeLimit;
							_this.formData.MissionScore = res.data.Score;
							_this.formData.StoreValue = res.data.StoreName;
							_this.formData.Introduce = res.data.Content;
							_this.formData.GroupValue = res.data.GroupName;
							_this.formData.MissionNumber = res.data.Number;
							_this.formData.Timevalue = res.data.Timing;
							_this.formData.CountValue = res.data.TimeLong;
							
						}else{
							_this.$message("网络异常，请重试")
						}
					})
			},
	        goBack(){
	        	if(this.$route.params.taskKind == '0'){
	        		this.$router.push('/Index')
	        	}else{
	        		this.$router.push('/WelfareTask')
	        	}

	        },
    }
   }
</script>

<style scoped="scoped">

.content_title {
	padding-bottom: 30px;
    font-size: 32px;
    color: #303A4F;
    font-weight: 100;
    display: flex;
    justify-content: space-between;
    align-items: baseline;
    
 }
 .formContent{
 	padding: 20px;
 	background: #FFFFFF;
 }
 .checkPicture{
 	display: inline-block;
 	width: 80px;
 	font-size: 30px;
 	font-weight: 100;
 	cursor: pointer;
 	line-height: 80px;
 	text-align: center;
 	height: 80px;
 	border:1px dashed #d9d9d9;
 	border-radius: 4px;
 }
 .el-form-item label{
 	color: #B0BAC9;
 	font-size: 16px;
 	line-height: 30px;
 }
 .el-input,.el-form-item__content{
 	line-height: 30px!important;
 }
 .iconUpload{
 	display: inline-block;
 	width: 60px;
 	height: 60px;
 	font-size: 30px!important;
 	text-align: center;
 	line-height: 60px!important;
 	border: dotted 1px #A1AAB4;
 	cursor: pointer;
 }
 .picItem {
 	display: inline-block;
 	width: 80px;
 	height: 80px;
 	margin: 0 5px;
 	vertical-align: top;
 }
 .picItem img{
 	width: 100%;
 	height: 100%;
 }
 .tipText{
   	color: indianred;
   }
</style>